var express = require('express');
var router = express.Router();
let fs = require('fs');
let xlsx = require('node-xlsx');
router.post('/', function(req, res) {
    let sendData = JSON.parse(req.body.content);//前端传输过来的数据
    let classGuid = req.body.classGuid;
    let tableData = [];
    let tableTitle =['',''];//第一列标题
    let tableTitle1 =['用户','账号']; //第二列标题
    const options = {'!cols': [{ wch: 18}, { wch: 18}]}; //设置表格宽度

    sendData[0].scoreItem.forEach(scoreItem=>{
        tableTitle1.push(`权重:${scoreItem.scoreWidth}`);
       tableTitle.push(scoreItem.scoreName);
    });
    tableTitle1.push('总成绩');
    tableData.push(tableTitle);
    tableData.push(tableTitle1);
    sendData.forEach(student=>{
       let tableContent = [student.name,student.number];
       student.scoreItem.forEach(scoreItem=>{
          tableContent.push(scoreItem.score);
       });
        tableContent.push(student.totalScore);
        tableData.push(tableContent);
    });
    let buffer = xlsx.build([{name: "mySheetName", data: tableData}],options);//生成buffer文件流
    fs.access(`./bin/public/export/grade_${classGuid}.xlsx`,err=>{
        if(err){
        //文件不存在
            //将buffer文件生成excel表格
            fs.writeFileSync(`./bin/public/export/grade_${classGuid}.xlsx`, buffer);
            res.send({path: `/bin/public/export/grade_${classGuid}.xlsx`});
        }else {
            //文件存在,删除文件
            fs.unlink(`./bin/public/export/grade_${classGuid}.xlsx`,err=>{
                //将buffer文件生成excel表格
                fs.writeFileSync(`./bin/public/export/grade_${classGuid}.xlsx`, buffer);
                res.send({path: `/bin/public/export/grade_${classGuid}.xlsx`});
            })
        }
    });
});
module.exports = router;
